window['isUp'] = false

const getServeVersion = (bk) => {
  // console.log('pageV.$route=======>', pageV.$route)
  const tempUrl = `${location.origin}/vesion.json?t=${Date.now()}`
  fetch(tempUrl).then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json(); // 如果响应是JSON格式
  }).then(data => {
    const newVersion = document.getElementById('version').innerHTML
    console.log(data.version, newVersion) // 处理数据   location.reload(true)
    localStorage.setItem('versionInfo', data.version)
    if (data.version != newVersion) {
      // location.reload(true)
    }
  }).then(() => {
    bk && bk()
  }).catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  })
}

// 获取版本信息
const getVersionInfo = () => {
  const userAgent = window.navigator.userAgent.toLowerCase()
  const isMobile = !!(userAgent.match(/(iPhone|iPad|iPod)/i) || userAgent.match(/Android/i) || userAgent.match(/Windows Phone/i) || userAgent.match(/IEMobile/i))
  // console.log('isUp=================>', window['isUp'], isMobile)
  if (isMobile == true) {
    return false
  }
  if (window['isUp'] === true) {
    return false
  }
  const upDateSystem = () => {
    // if (pageV) {
    //   pageV.$confirm({
    //     title: '系统更新提示',
    //     content: '当前系统已发布新版本，为了能让系统正常运行，请进行更新！',
    //     okText: '现在更新',
    //     cancelText: '稍后更新',
    //     onOk() {
    //       return new Promise((resolve, reject) => {
    //         window['isUp'] = false
    //         // localStorage.clear()
    //
    //       }).catch(() => console.log('Oops errors!'))
    //     },
    //     onCancel() { window['isUp'] = false }
    //   })
    // } else {
    //   window['isUp'] = false
    //   localStorage.clear()
    //   localStorage.setItem('versionInfo', newVersion)
    //   location.reload(true)
    //   window.close()
    // }
    window['isUp'] = false
    localStorage.setItem('versionInfo', newVersion)
    location.reload(true)
  }
  const newVersion = document.getElementById('version').innerHTML
  const versionInfo = localStorage.getItem('versionInfo')
  if (versionInfo) {
    if (newVersion !== versionInfo) {
      window['isUp'] = true
      upDateSystem()
    }
  } else {
    window['isUp'] = true
    upDateSystem()
  }
}

/**
 * 页面失活(无操作)
 * @param {() => void} callback 页面一定时长无操作时触发
 * @param {number} [timeout=15] 时长，默认15s，单位：秒
 * @param {boolean} [immediate=false] 是否立即开始，默认 false
 * @returns
 */
const pageDeactivated = (callback, timeout = 15, immediate = false) => {
  let pageTimer
  let beginTime = 0

  /**
   * 移除当前延时器，用户后续操作会重新开始计时
   */
  const onClearTimer = () => {
    pageTimer && clearTimeout(pageTimer)
    pageTimer = undefined
  }

  const onStartTimer = () => {
    const currentTime = Date.now()
    if (pageTimer && currentTime - beginTime < 100) {
      return
    }

    onClearTimer()
    beginTime = currentTime
    pageTimer = setTimeout(() => {
      callback()
    }, timeout * 1000)
  }

  const onPageVisibility = () => {
    // 页面显示状态改变时，移除延时器
    onClearTimer()

    if (document.visibilityState === 'visible') {
      const currentTime = Date.now()
      // 页面显示时，计算时间，如果超出限制时间则直接执行回调函数
      if (currentTime - beginTime >= timeout * 1000) {
        callback()
        return
      }
      // 继续计时
      pageTimer = setTimeout(() => {
        callback()
      }, timeout * 1000 - (currentTime - beginTime))
    }
  }

  const onStartDeactivated = () => {
    onStartTimer()
    // document.addEventListener('mousedown', onStartTimer)
    // document.addEventListener('mousemove', onStartTimer)
    document.addEventListener('visibilitychange', onPageVisibility)
  }

  const onStopDeactivated = () => {
    onClearTimer()
    // document.removeEventListener('mousedown', onStartTimer)
    // document.removeEventListener('mousemove', onStartTimer)
    document.removeEventListener('visibilitychange', onPageVisibility)
  }

  if (immediate) {
    onStartDeactivated()
  }

  return {
    onStartDeactivated,
    onStopDeactivated,
    onClearTimer
  }
}

document.addEventListener('visibilitychange', function () {
  if (document.hidden) {
    // console.log('当前标签页被切换到后台')
    // 当前标签页被切换到后台1
  } else {
    // 当前标签页被切换到前台
    // console.log('=======================标签页被切换到前台=======================')
    getServeVersion(() => {
      getVersionInfo()
    })
  }
})

// document.addEventListener('DOMContentLoaded', () => {
//   // console.log('hash:', location.hash)
//   getVersionInfo()
//   // console.log('=======================路由变化1=======================')
// })

// window.addEventListener('popstate', function (event) {
//   getServeVersion(() => {
//     getVersionInfo()
//   })
//   // 用户点击了后退按钮
//   // console.log('=======================后退按钮=======================')
// })

// function throttle(fn, threshhold) {
//   let last
//   let timer
//   threshhold || (threshhold = 250)
//   return function () {
//     let context = this
//     let args = arguments
//     let now = +new Date()
//     if (last && now < last + threshhold) {
//       clearTimeout(timer)
//       timer = setTimeout(function () {
//         last = now
//         fn.apply(context, args)
//       }, threshhold)
//     } else {
//       last = now
//       fn.apply(context, args)
//     }
//   }
// }

// window.onload = function () {
//   pageV && pageV.$watch('$route', (newRoute, oldRoute) => {
//     // 路由变化时执行的逻辑
//     getServeVersion(() => {
//       console.log('路由变化时执行的逻辑')
//       getVersionInfo()
//     })
//   })
// }

pageDeactivated(() => {
  getServeVersion(() => {
    getVersionInfo()
  })
  // console.log('=======================页面失活检查=======================', Date.now())
}, 60, true).onStartDeactivated()
